import org.springframework.beans.factory.BeanFactoryAware
import org.springframework.beans.factory.BeanFactory
import org.springframework.beans.BeansException

/**
 * use to extract basic blog information
 * and create a new Resource instance.
 */
class NewResourceProcess implements Runnable {

    def url
    def fetchService

    public void run() {
        println ("=============== ${url} ===============")
        // check for duplicate
        if (Resource.findByUrl(url)) {
            println "exist ${url}"
            return // do nothing
        } else {
            // test with/without '/' variant of the url
            def u
            if (url[-1] == '/') { // if url ended with '/' ?
                u = url[0..-2]    // remove ending '/'
            } else {
                u = url + '/'     // add ending '/'
            }
            if (Resource.findByUrl(u)) {
                println "equivalence exist ${u}"
                return
            }
        }
        
        def result = fetchService.fetch(url)
        def feed = ''        
        // get first feed that is not comment feed (crss)
        if (result.feeds) {
            feed = result.feeds.find { ! it.'@href'.equals('/crss') }?.'@href'
        }

        // if feed url is relative, make it absolute
        def m1 = feed =~ /((.+\:\/\/)?)(.*)/
        def feedProtocol = m1[0][1]
        def feedBody = m1[0][3]
        def m2 = url =~ /(.+\:\/\/[^\/]*)(.*)/
        def head = m2[0][1]
        def tail = m2[0][2]
        if (feedBody[0] == '/') {
            feed = head + feedBody
        } else {
            if (feedProtocol.size() == 0) {
                if (tail.size() > 0) {
                    def m = tail =~ /(.*)(\/)(.*)/
                    feed = head + m[0][1] + m[0][2] + feedBody
                } else {
                    feed = head + '/' + feedBody
                }
            }
        }

        def resource = new Resource(url: url,
                                    title: result.title,
                                    feedUrl: feed,
                                    lastUpdated: new java.sql.Timestamp(System.currentTimeMillis()))
        if (resource.hasErrors()) {
            resource.errors.allErrors.each {
                println it
            }
        } else {
            Resource.withTransaction { status ->
                resource.save()
                println ("save success")
            }
        }

    }
}
